<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 18:37:11
 * @email: ligui0506@sina.com
 * @descript: 工具类
 */

namespace App\Libraries;

class Utils
{
    /**
     * 嵌套结构
     *
     * @param  array        $data       数据源
     * @param  integer      $pid        父级ID
     * @param  string       $pkey       主键字段名称
     * @param  string       $fkey       父级ID字段名
     * @param  string       $child      子级数据KEY
     * @return array
     */
    public static function nesting(
        array $data = [],
        $pid = 0,
        string $pkey = 'id',
        string $fkey = 'pid',
        string $child = 'subMenu'
    ) {
        if (!is_array($data)) {
            return [];
        }

        $result = [];
        foreach ($data as $v) {
            if (!isset($v[$fkey])) {
                continue;
            }
            if ($v[$fkey] == $pid) {
                if (isset($v[$pkey])) {
                    $v[$child] = self::nesting($data, $v[$pkey], $pkey, $fkey, $child);
                }
                $result[] = $v;
            }
        }

        return $result;
    }

    /**
     * 单层树结构
     *
     * @param  array        $data       数据源
     * @param  integer      $pid        父级ID
     * @param  string       $pk         主键字段名称
     * @param  string       $fk         父级ID字段名
     * @param  string       $symbol     添加字符KEY
     * @param  integer      $level      级别
     * @return array
     */
    public static function layer(array $data = [], int $pid = 0, string $pkey = 'id', string $fkey = 'pid', string $symbol = 'symbol', int $level = 1)
    {
        if (!is_array($data)) {
            return [];
        }

        $result = [];
        foreach ($data as $v) {
            if ($v[$fkey] == $pid) {
                $v[$symbol] = $level > 1 ? '└' . str_repeat('─', ($level - 1) * 2) : '';
                $v['level'] = $level;

                $result[] = $v;
                $result   = array_merge($result, self::layer($data, $v[$pkey], $pkey, $fkey, $symbol, $level + 1));
            }
        }

        return $result;
    }

    /**
     * 所有子级ID
     *
     * @param  array        $data       数据源
     * @param  integer      $pid        父级ID
     * @return array
     */
    public static function childrenID(array $data, int $pid)
    {
        if (!is_array($data)) {
            return [];
        }

        $result = [];
        foreach ($data as $v) {
            if ($v['pid'] == $pid) {
                $result[] = $v['id'];
                $result   = array_merge($result, self::childrenID($data, $v['id']));
            }
        }

        return $result;
    }
}
